import { ref } from 'vue'
import { supabase } from '../lib/supabase'

export interface SearchSuggestion {
  text: string
  type: 'movie' | 'actor' | 'director' | 'genre' | null
  id?: number
}

export interface SearchFilters {
  genre: string
  universe: string
  language: string
  country: string
  ai: string
}

export function useSearch() {
  const isSearching = ref(false)
  const searchResults = ref<any[]>([])
  const suggestions = ref<SearchSuggestion[]>([])
  const recentSearches = ref<string[]>([])

  // 从localStorage加载最近搜索
  const loadRecentSearches = () => {
    const saved = localStorage.getItem('recentSearches')
    if (saved) {
      recentSearches.value = JSON.parse(saved)
    }
  }

  // 保存最近搜索到localStorage
  const saveRecentSearches = () => {
    localStorage.setItem('recentSearches', JSON.stringify(recentSearches.value))
  }

  // 添加最近搜索
  const addRecentSearch = (query: string) => {
    if (!query.trim()) return
    
    // 移除重复项
    const index = recentSearches.value.indexOf(query)
    if (index > -1) {
      recentSearches.value.splice(index, 1)
    }
    
    // 添加到开头
    recentSearches.value.unshift(query)
    
    // 限制数量
    if (recentSearches.value.length > 10) {
      recentSearches.value = recentSearches.value.slice(0, 10)
    }
    
    saveRecentSearches()
  }

  // 移除最近搜索
  const removeRecentSearch = (index: number) => {
    recentSearches.value.splice(index, 1)
    saveRecentSearches()
  }

  // 生成搜索建议
  const generateSuggestions = async (query: string) => {
    if (!query.trim()) {
      suggestions.value = []
      return
    }

    try {
      // 搜索电影标题
      const { data: movies } = await supabase
        .from('movies')
        .select('id, title')
        .ilike('title', `%${query}%`)
        .limit(3)

      // 搜索演员
      const { data: actorMovies } = await supabase
        .from('movies')
        .select('id, title, actors')
        .limit(3)

      // 搜索导演
      const { data: directorMovies } = await supabase
        .from('movies')
        .select('id, title, director')
        .ilike('director', `%${query}%`)
        .limit(3)

      const newSuggestions: SearchSuggestion[] = []

      // 添加电影建议
      if (movies && movies.length > 0) {
        movies.forEach(movie => {
          newSuggestions.push({
            text: movie.title,
            type: 'movie',
            id: movie.id
          })
        })
      }

      // 添加演员建议
      if (actorMovies && actorMovies.length > 0) {
        actorMovies.forEach(movie => {
          if (movie.actors && Array.isArray(movie.actors)) {
            movie.actors.forEach(actor => {
              if (actor.toLowerCase().includes(query.toLowerCase())) {
                newSuggestions.push({
                  text: `${actor} 主演的电影`,
                  type: 'actor'
                })
              }
            })
          }
        })
      }

      // 添加导演建议
      if (directorMovies && directorMovies.length > 0) {
        directorMovies.forEach(movie => {
          newSuggestions.push({
            text: `${movie.director} 导演的电影`,
            type: 'director'
          })
        })
      }

      // 添加类型建议
      const genres = ['剧情', '喜剧', '爱情', '动作', '恐怖', '科幻', '犯罪', '惊悚', '悬疑', '奇幻', '战争', '动画', '传记', '家庭', '歌舞', '历史', '冒险', '纪实', '灾难', '漫画改', '小说改']
      genres.forEach(genre => {
        if (genre.toLowerCase().includes(query.toLowerCase())) {
          newSuggestions.push({
            text: `${genre} 类型电影`,
            type: 'genre'
          })
        }
      })

      // 去重并限制数量
      const uniqueSuggestions = newSuggestions.filter((suggestion, index, self) => 
        index === self.findIndex(s => s.text === suggestion.text)
      ).slice(0, 8)

      suggestions.value = uniqueSuggestions
    } catch (error) {
      console.error('Error generating suggestions:', error)
      suggestions.value = []
    }
  }

  // 执行搜索
  const performSearch = async (query: string, filters: SearchFilters = {
    genre: 'all',
    universe: 'all',
    language: 'all',
    country: 'all',
    ai: 'all'
  }, sortBy: string = 'relevance', page: number = 0, limit: number = 20) => {
    if (!query.trim()) {
      searchResults.value = []
      return
    }

    isSearching.value = true
    addRecentSearch(query)

    try {
      let queryBuilder = supabase
        .from('movies_view')
        .select('*')

      // 基本搜索条件
      queryBuilder = queryBuilder.or(`title.ilike.%${query}%,description.ilike.%${query}%,plot.ilike.%${query}%`)

      // 应用筛选条件
      if (filters.genre !== 'all') {
        queryBuilder = queryBuilder.contains('genres', [filters.genre])
      }

      if (filters.universe !== 'all') {
        queryBuilder = queryBuilder.contains('universe', [filters.universe])
      }

      if (filters.language !== 'all') {
        queryBuilder = queryBuilder.contains('language', [filters.language])
      }

      if (filters.country !== 'all') {
        queryBuilder = queryBuilder.contains('country', [filters.country])
      }

      if (filters.ai !== 'all') {
        queryBuilder = queryBuilder.eq('is_ai', filters.ai === 'ai')
      }

      // 排序
      switch (sortBy) {
        case 'views':
          queryBuilder = queryBuilder.order('views', { ascending: false })
          break
        case 'rating':
          queryBuilder = queryBuilder.order('rating', { ascending: false })
          break
        case 'year':
          queryBuilder = queryBuilder.order('year', { ascending: false })
          break
        case 'updated_at':
          queryBuilder = queryBuilder.order('updated_at', { ascending: false })
          break
        default:
          // 相关度排序 - 这里可以根据搜索关键词的匹配度来排序
          queryBuilder = queryBuilder.order('views', { ascending: false })
      }

      // 分页
      queryBuilder = queryBuilder.range(page * limit, (page + 1) * limit - 1)

      const { data, error } = await queryBuilder

      if (error) {
        console.error('Search error:', error)
        searchResults.value = []
      } else {
        // 转换数据格式
        searchResults.value = (data || []).map(movie => ({
          id: movie.id,
          title: movie.title,
          coverUrl: movie.cover_url,
          rating: movie.rating,
          tags: movie.user_tags || [],
          isAi: movie.is_ai,
          views: movie.views,
          year: movie.year,
          updatedAt: movie.updated_at,
          genres: movie.genres || [],
          universe: Array.isArray(movie.universe) ? movie.universe[0] : movie.universe || null,
          language: Array.isArray(movie.language) ? movie.language[0] : movie.language || null,
          country: Array.isArray(movie.country) ? movie.country[0] : movie.country || null
        }))
      }
    } catch (error) {
      console.error('Error performing search:', error)
      searchResults.value = []
    } finally {
      isSearching.value = false
    }
  }

  // 清除搜索
  const clearSearch = () => {
    searchResults.value = []
    suggestions.value = []
  }

  return {
    isSearching,
    searchResults,
    suggestions,
    recentSearches,
    loadRecentSearches,
    addRecentSearch,
    removeRecentSearch,
    generateSuggestions,
    performSearch,
    clearSearch
  }
} 